package com.spring.controller.web.interceptors;

import com.base.annotations.Token;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.UUID;

/**
 * Created by chenhs on 2018/6/14.
 *
 * 一直有问题：
 * https://bbs.csdn.net/topics/391843354
 *
 */
public class TokenInterceptor extends HandlerInterceptorAdapter {

    private static final Logger logger = LoggerFactory.getLogger(TokenInterceptor.class);

    private static final String TOKEN = "token";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("this is interceptor...");
        if (handler instanceof HandlerMethod) {
            Method method = ((HandlerMethod) handler).getMethod();
            Token annotation = method.getAnnotation(Token.class);
            if (annotation != null) {
                HttpSession session = request.getSession();

                //创建token
                boolean create = annotation.create();
                if (create) {
                    session.setAttribute(TOKEN, UUID.randomUUID().toString());
                    return true;
                }

                //删除token
                boolean remove = annotation.remove();
                if (remove) {
                    if (isRepeatSubmit(request)) {
                        logger.warn("表单不能重复提交：" + request.getRequestURL());
                        return false;
                    }
                    session.removeAttribute(TOKEN);
                }
            }
        } else {
            return super.preHandle(request, response, handler);
        }

        return true;
    }

    private boolean isRepeatSubmit(HttpServletRequest request) {
        String token = (String) request.getSession().getAttribute(TOKEN);
        if (token == null) {
            return true;
        }

        String reqToken = request.getParameter(TOKEN);
        if (reqToken == null) {
            return true;
        }

        if (!token.equals(reqToken)) {
            return true;
        }

        return false;
    }
}
